import { logger } from './logger'

class WebSocketManager {
  constructor() {
    this.ws = null
    this.token = localStorage.getItem('authToken') || null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
    this.messageQueue = []
    this.messageCallbacks = new Map()
  }

  connect() {
    return new Promise((resolve, reject) => {
      try {
        this.ws = new WebSocket('ws://192.168.1.16:8000/projectimmi')

        this.ws.onopen = () => {
          this.reconnectAttempts = 0
          this.processMessageQueue()
          resolve()
        }

        this.ws.onmessage = (event) => {
          console.log('WebSocket raw message:', event.data)
          const response = JSON.parse(event.data)
          console.log('WebSocket parsed response:', response)
          logger.logResponse({
            status: response.status,
            data: response
          })

          // 处理登录响应，保存token
          if (response.operation === 'user_login' && response.status === 1) {
            this.token = response.authToken
            localStorage.setItem('authToken', this.token)
          }

          // 调用对应的回调函数
          const callback = this.messageCallbacks.get(response.requestID)
          if (callback) {
            callback(response)
            this.messageCallbacks.delete(response.requestID)
          }
        }

        this.ws.onclose = () => {
          if (this.reconnectAttempts < this.maxReconnectAttempts) {
            setTimeout(() => this.reconnect(), this.reconnectInterval)
          }
        }

        this.ws.onerror = (error) => {
          logger.logError(error)
          reject(error)
        }
      } catch (error) {
        logger.logError(error)
        reject(error)
      }
    })
  }

  reconnect() {
    this.reconnectAttempts++
    this.connect()
  }

  sendMessage(message) {
    console.log('WebSocket connection state:', this.ws?.readyState)
    console.log('Current message queue:', this.messageQueue.length)
    return new Promise((resolve, reject) => {
      const requestID = Date.now().toString()
      message.requestID = requestID
      
      if (this.token) {
        message.authToken = this.token
      }

      logger.logRequest({
        url: 'WebSocket',
        method: 'SEND',
        data: message
      })

      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.messageCallbacks.set(requestID, resolve)
        this.ws.send(JSON.stringify(message))
      } else {
        this.messageQueue.push({ message, resolve, reject })
        if (!this.ws || this.ws.readyState === WebSocket.CLOSED) {
          this.connect()
        }
      }
    })
  }

  processMessageQueue() {
    while (this.messageQueue.length > 0) {
      const { message, resolve, reject } = this.messageQueue.shift()
      this.sendMessage(message).then(resolve).catch(reject)
    }
  }

  close() {
    if (this.ws) {
      this.ws.close()
    }
  }
}

export const wsManager = new WebSocketManager()